import React, { Component } from "react";
import {
    StatusBar, DeviceEventEmitter
} from 'react-native';
import { NavigationContainer, DefaultTheme } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { SafeAreaProvider } from "react-native-safe-area-context";
import actions from '../action'
import { connect } from 'react-redux'
import Screens from './Screens'
import Constant from '../utils/Constant'
import { registerApp } from '../../src/utils/WeChatUtils'//微信支付

import OpenIMSDKRN, { OpenIMEmitter } from 'open-im-sdk-rn';
import RNFS from 'react-native-fs';
import JPush from 'jpush-react-native';

const MyTheme = {
    ...DefaultTheme,
    colors: {
        ...DefaultTheme.colors,
        primary: '#333333',
        text: '#333333',
        card: '#ffffff',
        background: '#ffffff',
        border: '#e4e4e4'
    },
};

// const Stack = createStackNavigator();
const Stack = createNativeStackNavigator();


class RootStack extends Component {

    componentDidMount() {
        if (Constant.userInfo.username) {
            this.initImSDK();
        }

        setTimeout(() => {
            registerApp();//微信初始化
        }, 1000);

        this.registerJPush()
    }

    componentWillUnmount() {
        OpenIMEmitter.removeAllListeners('onRecvNewMessages');
        OpenIMEmitter.removeAllListeners('onConnecting');
        OpenIMEmitter.removeAllListeners('onConnectSuccess');
        OpenIMEmitter.removeAllListeners('onConnectFailed');
        OpenIMEmitter.removeAllListeners('onKickedOffline');
    }

    render() {
        // const { logininfo } = this.props;     //redux中的登录信息
        return (
            <SafeAreaProvider>
                <NavigationContainer theme={MyTheme}>
                    <StatusBar barStyle="dark-content" backgroundColor="#ffffff" />
                    <Stack.Navigator
                        screenOptions={{
                            headerShown: false,
                            headerStyle: {
                                backgroundColor: '#f4511e',
                            },
                            headerTintColor: '#fff',
                            headerTitleStyle: {
                                fontWeight: 'bold',
                            }
                        }}
                    >
                        {this.MainPage()}
                    </Stack.Navigator>
                </NavigationContainer>
            </SafeAreaProvider>
        )
    }

    initImSDK() {
        RNFS.mkdir(`${RNFS.DocumentDirectoryPath}/tmp`);
        OpenIMSDKRN.initSDK(
            {
                apiAddr: Constant.imApiAddr,
                wsAddr: Constant.imWsAddr,
                dataDir: `${RNFS.DocumentDirectoryPath}/tmp`,
                logLevel: 5,
                isLogStandardOutput: true,
            },
            Constant.userInfo.username,
        )
            .then(() => {
                console.log('openImLogin', `initSDK success`);
                this.addMsgListener();
                setTimeout(() => {
                    this.openImLogin();
                }, 1000);

            })
            .catch((error) => {
                console.log("openImLogin-initSDK error", error);
            });
    };

    openImLogin() {
        console.log('openImLogin', Constant.userInfo.imUserId + '');
        OpenIMSDKRN.getLoginStatus(Constant.userInfo.username).then((result) => {
            console.log('openImLogin-getLoginStatus', result);
            if (result == 1) {
                OpenIMSDKRN.login({
                    userID: Constant.userInfo.imUserId,
                    token: Constant.userInfo.imToken,
                }, Constant.userInfo.username)
                    .then((result) => {
                        console.log('openImLogin-success', result);

                    }).catch(err => {
                    console.log('openImLogin-error=', err);
                });
            } else if (result == 3) {

            }
        })
    }

    addMsgListener() {
        OpenIMEmitter.addListener('onRecvNewMessages', (data) => {
            console.log('onRecvNewMessages', data);

            DeviceEventEmitter.emit('updateUnreadMsg', data);


        });
        OpenIMEmitter.addListener('onConnecting', () => {
            console.log('OpenIMEmitter', 'onConnecting');
        });

        OpenIMEmitter.addListener('onConnectSuccess', () => {
            console.log('OpenIMEmitter', 'onConnectSuccess');

        });

        OpenIMEmitter.addListener('onConnectFailed', ({ errCode, errMsg }) => {
            console.log('OpenIMEmitter', 'onConnectFailed', errCode, errMsg);
        });
        OpenIMEmitter.addListener('onKickedOffline', (data) => {

            // OpenIMSDKRN.logout(Constant.userInfo.username)
            //     .then(() => {
            //         console.log('IM账号退出成功')

            //     })
            //     .catch(({ errCode, errMsg }) => {
            //         console.log('IM账号退出失败')
            //         console.log('logout', errCode + '-' + errMsg)

            //     });
        });
    }

    registerJPush() {
        JPush.setLoggerEnable(true)
        JPush.init({ "appKey": "f982e2232c240654df5c5107", "channel": "default_developer", "production": 1 });
        //连接状态
        this.connectListener = result => {
            console.log("connectListener:" + JSON.stringify(result))
        };
        JPush.addConnectEventListener(this.connectListener);
        //通知回调
        this.notificationListener = result => {
            console.log("notificationListener:" + JSON.stringify(result))
        };
        JPush.addNotificationListener(this.notificationListener);
        //本地通知回调
        this.localNotificationListener = result => {
            console.log("localNotificationListener:" + JSON.stringify(result))
        };
        JPush.addLocalNotificationListener(this.localNotificationListener);

        this.localNotificationListener = result => {
            console.log("localNotificationListener:" + JSON.stringify(result))
        };
        // JPush.onAliasOperatorResult = result => {
        //     console.error("onAliasOperatorResult:" + JSON.stringify(result))
        // };
        // JPush.addLocalNotificationListener(this.localNotificationListener);
        //自定义消息回调
        // this.customMessageListener = result => {
        //     console.log("customMessageListener:" + JSON.stringify(result))
        // };
        // JPush.addCustomMessagegListener(this.customMessageListener);
        //tag alias事件回调
        this.tagAliasListener = result => {
            console.log("tagAliasListener==:" + JSON.stringify(result))
        };
        JPush.addTagAliasListener(this.tagAliasListener);
        //手机号码事件回调
        this.mobileNumberListener = result => {
            console.log("mobileNumberListener:" + JSON.stringify(result))
        };
        JPush.addMobileNumberListener(this.mobileNumberListener);

        JPush.setAlias({ alias: Constant.userInfo.userId + '', sequence: Constant.userInfo.userId });

        JPush.getRegistrationID((res) => {
            console.log('getRegistrationID', res);
            Constant.registrationID = res.registerID

        })
    }

    MainPage() {

        const screenConfigs = [
            { name: "MainTab", component: Screens.MainPage, title: '主页' },
            { name: "PublishCarPage", component: Screens.PublishCarPage, title: '发布车辆' },
            { name: "CarPublishSuccessPage", component: Screens.CarPublishSuccessPage, title: '发布车辆成功页面' },
            { name: "FoursQuery", component: Screens.FoursQuery, title: '维保查询' },
            { name: "FoursQuerySubmit", component: Screens.FoursQuerySubmit, title: '维保提交' },
            { name: "FoursQueryHistory", component: Screens.FoursQueryHistory, title: '维保记录' },
            { name: "FoursQueryCostRecord", component: Screens.FoursQueryCostRecord, title: '维保订单' },
            { name: "FoursCarSelectPage", component: Screens.FoursCarSelectPage, title: '维保车辆选择' },
            { name: "WebView", component: Screens.WebView, title: 'web页' },
            { name: "FeedBack", component: Screens.FeedBack, title: '意见反馈' },
            { name: "UserInfoPage", component: Screens.UserInfoPage, title: '个人资料' },
            { name: "ModifyUserInfo", component: Screens.ModifyUserInfo, title: '修改用户信息' },
            { name: "ContactUs", component: Screens.ContactUs, title: '平台客服' },
            { name: "Setting", component: Screens.Setting, title: '设置' },
            { name: "AccountLogOff", component: Screens.AccountLogOff, title: '账号注销' },
            { name: "AccountLogOffSubmit", component: Screens.AccountLogOffSubmit, title: '账号注销验证' },
            { name: "AboutShuaiche", component: Screens.AboutShuaiche, title: '关于帅车' },
            { name: "CompanyEmployee", component: Screens.CompanyEmployee, title: '员工管理' },
            { name: "CompanyEmployeeDetail", component: Screens.CompanyEmployeeDetail, title: '员工详情' },
            { name: "CompanyEmployeeEdit", component: Screens.CompanyEmployeeEdit, title: '编辑员工' },
            { name: "CompanyDutyList", component: Screens.CompanyDutyList, title: '职务选择' },
            { name: "DutyManager", component: Screens.DutyManager, title: '职务管理' },
            { name: "DutyDetail", component: Screens.DutyDetail, title: '职务详情' },
            { name: "DutyOperation", component: Screens.DutyOperation, title: '职务编辑' },
            { name: "StoreInfo", component: Screens.StoreInfo, title: '门店详情' },
            { name: "StoreEdit", component: Screens.StoreEdit, title: '门店设置' },
            { name: "SwitchAPI", component: Screens.SwitchAPI, title: 'API环境切换' },
            { name: "CarColorPage", component: Screens.CarColorPage, title: '车辆颜色' },
            { name: "RadioBoxPage", component: Screens.RadioBoxPage, title: '类型选择' },
            { name: "CarConfigurationPage", component: Screens.CarConfigurationPage, title: '车辆配置' },
            { name: "SellerSelectPage", component: Screens.SellerSelectPage, title: '收购员' },
            { name: "CarDetailPage", component: Screens.CarDetailPage, title: '车辆详情' },
            { name: "CarRecordPage", component: Screens.CarRecordPage, title: '车辆档案' },
            { name: "CarConfigPage", component: Screens.CarConfigPage, title: '参数配置' },
            { name: "CarTrackPage", component: Screens.CarTrackPage, title: '车辆轨迹' },
            { name: "CarReturnStockPage", component: Screens.CarReturnStockPage, title: '车辆回库' },
            { name: "BigImageViewer", component: Screens.BigImageViewer, title: '图片查看' },
            { name: "CarStockListPage", component: Screens.CarStockListPage, title: '车辆管理' },
            { name: "CarBookPage", component: Screens.CarBookPage, title: '车辆预定' },
            { name: "CarDetectionPage", component: Screens.CarDetectionPage, title: '检测下单' },
            { name: "CarPriceSettingPage", component: Screens.CarPriceSettingPage, title: '设置价格' },
            { name: "CarOutStockPage", component: Screens.CarOutStockPage, title: '销售出库' },
            { name: "CarOperateSuccessPage", component: Screens.CarOperateSuccessPage, title: '操作成功' },
            { name: "CarCancelStockPage", component: Screens.CarCancelStockPage, title: '车辆退库' },
            { name: "CarFoursReportPage", component: Screens.CarFoursReportPage, title: '车辆维保记录列表' },
            { name: "CarFoursPicReportPage", component: Screens.CarFoursPicReportPage, title: '车辆维保图片记录' },
            { name: "CarDetectionReportPage", component: Screens.CarDetectionReportPage, title: '车辆检测记录' },
            { name: "FundAccountPage", component: Screens.FundAccountPage, title: '资金账户' },
            { name: "BondAccountPage", component: Screens.BondAccountPage, title: '保证金账户' },
            { name: "WalletHistoryPage", component: Screens.WalletHistoryPage, title: '费用明细' },
            { name: "ConfirmPayPage", component: Screens.ConfirmPayPage, title: '确认支付' },
            { name: "BankCardManagerPage", component: Screens.BankCardManagerPage, title: '银行卡管理' },
            { name: "BankCardSelectPage", component: Screens.BankCardSelectPage, title: '银行卡选择' },
            { name: "BankCardAddPage", component: Screens.BankCardAddPage, title: '添加银行卡' },
            { name: "SignSettingsPage", component: Screens.SignSettingsPage, title: '签署设置' },
            { name: "AddAuthorizePage", component: Screens.AddAuthorizePage, title: '添加授权' },
            { name: "ContractListPage", component: Screens.ContractListPage, title: '电子合同' },
            { name: "ContractDetailPage", component: Screens.ContractDetailPage, title: '合同详情' },
            { name: "ContractRechargePage", component: Screens.ContractRechargePage, title: '合同充值' },
            { name: "ChooseAlreadyAuthorizePage", component: Screens.ChooseAlreadyAuthorizePage, title: '选择企业' },
            { name: "SignatoryPage", component: Screens.SignatoryPage, title: '填写签署方' },
            { name: "FillContractPage", component: Screens.FillContractPage, title: '填写合同' },
            { name: "ChooseCustomersPage", component: Screens.ChooseCustomersPage, title: '选择客户' },
            { name: "AttachmentImagePage", component: Screens.AttachmentImagePage, title: '合同附件选择' },
            { name: "ConfirmInfosPage", component: Screens.ConfirmInfosPage, title: '信息确认' },
            { name: "PrivewContractPage", component: Screens.PrivewContractPage, title: '合同预览' },
            { name: "ChooseTemplatePage", component: Screens.ChooseTemplatePage, title: '选择合同模板' },
            { name: "DetectionListPage", component: Screens.DetectionListPage, title: '检测中心' },
            { name: "DetectionDetailPage", component: Screens.DetectionDetailPage, title: '检测详情' },
            { name: "SearchPage", component: Screens.SearchPage, title: '关键字输入' },
            { name: "MoreFilterPage", component: Screens.MoreFilterPage, title: '更多' },
            { name: "CarOfferPricePage", component: Screens.CarOfferPricePage, title: '车辆报价' },
            { name: "StartOrderPage", component: Screens.StartOrderPage, title: '发起订单' },
            { name: "CarOfferPriceDetailPage", component: Screens.CarOfferPriceDetailPage, title: '报价详情' },
            { name: "MessageChat", component: Screens.MessageChat, title: '消息聊天' },
            { name: "CarOfferPriceHistoryPage", component: Screens.CarOfferPriceHistoryPage, title: '报价记录' },
            { name: "BuyerStartOrderPage", component: Screens.BuyerStartOrderPage, title: '买家报价确认' },
            { name: "ModifyInputPage", component: Screens.ModifyInputPage, title: '通用修改编辑' },
            { name: "CompanyDetailPage", component: Screens.CompanyDetailPage, title: '商家主页' },
            { name: "CompanyInfoPage", component: Screens.CompanyInfoPage, title: '商家详情' },
            { name: "SelectShareCarListPage", component: Screens.SelectShareCarListPage, title: '选择分享车辆' },
            { name: "OrderListPage", component: Screens.OrderListPage, title: '订单列表' },
            { name: "NormalOrderDetail", component: Screens.NormalOrderDetail, title: '订单详情' },
            { name: "ApplySaleServicePage", component: Screens.ApplySaleServicePage, title: '申请售后' },
            { name: "ApplySaleServiceSubmitPage", component: Screens.ApplySaleServiceSubmitPage, title: '申请售后' },
            { name: "NoticeMsgListPage", component: Screens.NoticeMsgListPage, title: '通知消息' },
            { name: "ModifyAddressInfoPage", component: Screens.ModifyAddressInfoPage, title: '发/收货地址修改' },
            { name: "LogisticsOrderingSubmitPage", component: Screens.LogisticsOrderingSubmitPage, title: '物流下单' },
            { name: "LogisticsTrackPage", component: Screens.LogisticsTrackPage, title: '物流动态' },
            { name: "UploadPayInfoPage", component: Screens.UploadPayInfoPage, title: '上传支付凭证' },
            { name: "OrderSearchPage", component: Screens.OrderSearchPage, title: '订单搜索' },
            { name: "SignMainBodyPage", component: Screens.SignMainBodyPage, title: '选择签署主体' },
            { name: "ConfirmReceivePayPage", component: Screens.ConfirmReceivePayPage, title: '确认收款' },
            { name: "AfterSaleOrderDetail", component: Screens.AfterSaleOrderDetail, title: '售后订单详情' },
            { name: "ModifyPricePage", component: Screens.ModifyPricePage, title: '修改订单价格' },
            { name: "ConfirmReceiveCar", component: Screens.ConfirmReceiveCar, title: '确认收货' },
            { name: "StrictCarListPage", component: Screens.StrictCarListPage, title: '严选车源' },
            { name: "JoinCarListPage", component: Screens.JoinCarListPage, title: '加盟车源' },
            { name: "SeekingListPage", component: Screens.SeekingListPage, title: '求购列表' },
            { name: "BuyerListPage", component: Screens.BuyerListPage, title: '买手列表' },
            { name: "SelectStorePage", component: Screens.SelectStorePage, title: '门店选择' },
            { name: "BuyerSetLabelPage", component: Screens.BuyerSetLabelPage, title: '买手设置标签' },
            { name: "BuyerDetailPage", component: Screens.BuyerDetailPage, title: '买手主页' },
            { name: "BuyerInfoPage", component: Screens.BuyerInfoPage, title: '买手详情' },
            { name: "ApplyCarFormPage", component: Screens.ApplyCarFormPage, title: '买手求购' },
            { name: "SeekingDetailPage", component: Screens.SeekingDetailPage, title: '求购详情' },
            { name: "SeekingInfoPage", component: Screens.SeekingInfoPage, title: '求购详情' },
            { name: "SeekMoreFilterPage", component: Screens.SeekMoreFilterPage, title: '更多' },
            { name: "SeekingCarPage", component: Screens.SeekingCarPage, title: '选车推荐' },
            { name: "InFormPage", component: Screens.InFormPage, title: '投诉举报' },
            { name: "MyOfferPriceListPage", component: Screens.MyOfferPriceListPage, title: '我的报价' },
            { name: "PreferenceCarListPage", component: Screens.PreferenceCarListPage, title: '偏好车源' },
            { name: "BuyerStartFullOrderPage", component: Screens.BuyerStartFullOrderPage, title: '全款预付确认' },
        ];

        return (
            <>
                {screenConfigs.map(config => (
                    <Stack.Screen
                        key={config.name}
                        name={config.name}
                        component={config.component}
                        options={{ title: config.title }}
                    />
                ))}
            </>
        )
    }
}

// 将redux中数据传到视图层（state为redux中所有数据）
const mapStateToProps = state => ({
    logininfo: state.logininfo,
    version: state.version,
    useragent: state.useragent,
});

// 视图层改变redux数据操作
const mapDispatchToProps = dispatch => ({
    addLoginInfo: (value) => dispatch(actions.addLoginInfo(value)),
    addVersion: (value) => dispatch(actions.addVersion(value)),
    addUseragent: (value) => dispatch(actions.addUseragent(value)),
});

export default connect(mapStateToProps, mapDispatchToProps)(RootStack);